<?php
/*
* 2007-2012 PrestaShop
*
* NOTICE OF LICENSE
*
* This source file is subject to the Open Software License (OSL 3.0)
* that is bundled with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://opensource.org/licenses/osl-3.0.php
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade PrestaShop to newer
* versions in the future. If you wish to customize PrestaShop for your
* needs please refer to http://www.prestashop.com for more information.
*
*  @author PrestaShop SA <contact@prestashop.com>
*  @copyright  2007-2012 PrestaShop SA
*  @version  Release: $Revision: 17889 $
*  @license    http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
*  International Registered Trademark & Property of PrestaShop SA
*/

class AdminStockPsfControllerCore extends AdminController
{
	
	

	public function __construct()
	{
		$this->context = Context::getContext();
		$this->table = 'product';
		$this->className = 'Product';
		$this->lang = false;
		$this->multishop_context = Shop::CONTEXT_ALL;

		$this->fields_list = array(
			'reference' => array(
				'title' => $this->l('Reference'),
				'align' => 'center',
				'width' => 200,
				'havingFilter' => true
			)
			,
			'name' => array(
				'title' => $this->l('Name'),

			),
			'physical_quantity' => array(
				'title' => $this->l('Available quantity'),
				'width' => 80,
				'orderby' => true,
				'search' => false
			),
				
			'alert_quantity' => array(
						'title' => $this->l('Alert quantity'),
						'width' => 80,
						'orderby' => true,
						'search' => false
				)

		);

		
		parent::__construct();
		
		// overrides confirmation messages specifically for this controller
		$this->_conf = array(
				1 => $this->l('The product was successfully added to stock'),
				2 => $this->l('The product was successfully removed from the stock'),
				3 => $this->l('The transfer was successfully completed'),
		);
		
		parent::__construct();
	}
	
	
	/**
	 * AdminController::renderList() override
	 * @see AdminController::renderList()
	 */
	public function renderList()
	{
		// sets actions
		$this->addRowAction('details');
		//$this->addRowAction('addstock');
		$this->addRowAction('removestock');
		
		// no link on list rows
		$this->list_no_link = true;
	
		// inits toolbar
		$this->toolbar_btn = array();
	
		// overrides query
		// query
		
		$this->_select = '
		a.id_product as id, 
		pl.name as name,
		
		COUNT(pa.id_product_attribute) as variations';
		$this->_join = 'LEFT JOIN `'._DB_PREFIX_.'product_attribute` pa ON (pa.id_product = a.id_product)'.Shop::addSqlAssociation('product_attribute', 'pa', false);
		$this->_join .= ' LEFT JOIN `'._DB_PREFIX_.'product_lang` pl ON (
		a.id_product = pl.id_product
		AND pl.id_lang = '.(int)$this->context->language->id.'
		)';
		$this->_where = 'AND a.cache_is_pack = 1 AND a.is_virtual = 0';
		$this->_group = 'GROUP BY a.id_product';
		
		
		// sets toolbar
		$this->initToolbar();

		$list = parent::renderList();

		return $list;
	}
	
	
	/**
	 * AdminController::getList() override
	 * @see AdminController::getList()
	 */
	public function getList($id_lang, $order_by = null, $order_way = null, $start = 0, $limit = null, $id_lang_shop = false)
	{
	
		
	
		parent::getList($id_lang, $order_by, $order_way, $start, $limit, $id_lang_shop);
	
		
		$nb_items = count($this->_list);
		for ($i = 0; $i < $nb_items; ++$i)
		{
			$item = &$this->_list[$i];
			$item[$this->identifier] = $item['id_product'];
			
			$pack_quantity = null;
			
			// if product is a pack
			
			$pack_quantity=$this->getAvailablePackQuantity((int)$item['id_product']);
			
			
			
			$item['physical_quantity']=$pack_quantity;
			
			
			
			
			$item['alert_quantity']=$item['minimal_quantity'];
		
		}
	
		
	}
	
	
	
	
	
	
	/**
	 * method call when ajax request is made with the details row action
	 * @see AdminController::postProcess()
	 */
	public function ajaxProcessDetails()
	{
		
		$this->display='pack';
		$this->tpl_form = strtolower($this->display).'.tpl';
		$data = $this->createTemplate($this->tpl_form);
		
		$id = Tools::getValue('id');
		$product = new Product($id, true, $this->context->language->id);
		
		$product->packItems = Pack::getItemTable($product->id, $this->context->language->id);
		//Pack::getItems($product->id, $this->context->language->id);
		$pack_items = $this->getPackItems($product);//$product->packItems;
		//$this->getPackItems($product);

		$data->assign(array(
				'pack_items' => $pack_items
		));
		
		//echo $data->fetch();
		echo Tools::jsonEncode(array('use_parent_structure'=>false,'data'=> $data->fetch()));
		die;
		
	}
	
	

	/**
	 * AdminController::renderForm() override
	 * @see AdminController::renderForm()
	 */
	/*public function renderForm()
	{
		
		// gets the product
		$id_product = (int)Tools::getValue('id');
		
		// switch, in order to display the form corresponding to the current action
		switch ($this->display)
		{
			
			case 'removestock' :
				$this->fields_form[]['form'] = array(
				'legend' => array(
				'title' => $this->l('Remove product from stock'),
				'image' => '../img/admin/remove_stock.png'
				),
				'input' => array(
				array(
				'type' => 'hidden',
				'name' => 'is_post',
				),
				array(
				'type' => 'hidden',
				'name' => 'id_product',
				),
				array(
				'type' => 'hidden',
				'name' => 'id_product_attribute',
				),
				array(
				'type' => 'hidden',
				'name' => 'check',
				),
				array(
				'type' => 'text',
				'label' => $this->l('Product reference:'),
				'name' => 'reference',
				'size' => 30,
				'disabled' => true,
				),
				array(
				'type' => 'text',
				'label' => $this->l('EAN13:'),
				'name' => 'ean13',
				'size' => 15,
				'disabled' => true,
				),
				array(
				'type' => 'text',
				'label' => $this->l('Name:'),
				'name' => 'name',
				'size' => 75,
				'disabled' => true,
				),
				array(
				'type' => 'text',
				'label' => $this->l('Quantity to remove:'),
				'name' => 'quantity',
				'size' => 10,
				'maxlength' => 6,
				'required' => true,
				'desc' => $this->l('Physical quantity to remove'),
				),
				array(
				'type' => 'radio',
				'label' => $this->l('Usable for sale:'),
				'name' => 'usable',
				'required' => true,
				'class' => 't',
				'is_bool' => true,
				'values' => array(
				array(
				'id' => 'active_on',
				'value' => 1,
				'label' => $this->l('Enabled')
				),
				array(
				'id' => 'active_off',
				'value' => 0,
				'label' => $this->l('Disabled')
				)
				),
				'desc' => $this->l('Do you want to remove this quantity from the usable quantity (yes) or the physical quantity (no)?')
				),
				array(
				'type' => 'select',
				'label' => $this->l('Warehouse:'),
				'name' => 'id_warehouse',
				'required' => true,
				'options' => array(
				'query' => $warehouses_remove,
				'id' => 'id_warehouse',
				'name' => 'name'
				),
				'desc' => $this->l('Select the warehouse from where you want to remove the product')
				),
				array(
				'type' => 'select',
				'label' => $this->l('Label:'),
				'name' => 'id_stock_mvt_reason',
				'required' => true,
				'options' => array(
				'query' => StockMvtReason::getStockMvtReasonsWithFilter($this->context->language->id,
				array(Configuration::get('PS_STOCK_MVT_TRANSFER_FROM')),
				-1),
				'id' => 'id_stock_mvt_reason',
				'name' => 'name'
				),
				'desc' => $this->l('Label used in stock movements'),
				),
				),
				'submit' => array(
				'title' => $this->l('Remove from stock'),
				'class' => 'button'
				)
				);
				break;
					
		}
	}*/
	
	// init form
	/*$this->renderForm();
	 $this->getlanguages();
	
	$helper = new HelperForm();
	
	// Check if form template has been overriden
	if (file_exists($this->context->smarty->getTemplateDir(0).'/'.$this->tpl_folder.'form.tpl'))
		$helper->tpl = $this->tpl_folder.'form.tpl';
	
	$this->setHelperDisplay($helper);
	$helper->submit_action = $this->display;
	$helper->id = null; // no display standard hidden field in the form
	$helper->languages = $this->_languages;
	$helper->default_form_language = $this->default_form_language;
	$helper->allow_employee_form_lang = $this->allow_employee_form_lang;
	
	$helper->fields_value = array(
			'id_product' => $id_product,
			'is_post' => 1,
	);
	
	
	$content= $helper->generateForm($this->fields_form);
	
	$this->context->smarty->assign(array(
			'content' => $content
	));
	
	*/
	
	/**
	 * method call when ajax request is made with the details row action
	 * @see AdminController::postProcess()
	 */
	public function ajaxProcessRemoveStock()
	{
	
		$id = Tools::getValue('id');
		
		$data=$this->createTemplate('removestock.tpl');
		
		
		
		$id = Tools::getValue('id');
		$product = new Product($id, true, $this->context->language->id);
		
		
		$id = Tools::getValue('id');
		$product = new Product($id, true, $this->context->language->id);
		
		// If pack items have been submitted, we want to display them instead of the actuel content of the pack
		// in database. In case of a submit error, the posted data is not lost and can be sent again.
		if (Tools::getValue('namePackItems'))
		{
			$input_pack_items = Tools::getValue('inputPackItems');
			$input_namepack_items = Tools::getValue('namePackItems');
			$pack_items = $this->getPackItems();
		}
		else
		{
			$product->packItems = Pack::getItemTable($product->id, $this->context->language->id);
			$pack_items = $this->getPackItems($product);
			$input_namepack_items = '';
			$input_pack_items = '';
			foreach ($pack_items as $pack_item)
			{
				$input_pack_items .= $pack_item['pack_quantity'].'x'.$pack_item['id'].'-';
				$input_namepack_items .= $pack_item['pack_quantity'].' x '.$pack_item['name'].'¤';
			}
		}
		
		
		
		if (!array_key_exists('RemoveStock', self::$cache_lang))
			self::$cache_lang['RemoveStock'] = $this->l('RemoveStock', 'Helper');
		
		$ajax_params = $this->ajax_params;
		if (!is_array($ajax_params) || !isset($ajax_params['action']))
			$ajax_params['action'] = 'removestock';
		
		
		$data->assign(array(
				'product' => $product,
				'input_pack_items' => $input_pack_items,
				'curPackAvailQty' => $this->getAvailablePackQuantity($product->id),
				
				'input_namepack_items' => $input_namepack_items,
				'pack_items' => $pack_items,
				'product_type' => (int)Tools::getValue('type_product', $product->getType())
				
				,'id' => Tools::safeOutput($id),
				'controller' => str_replace('Controller', '', get_class($this->context->controller)),
				'token' => Tools::safeOutput($token != null ? $token : $this->token),
				'action' => self::$cache_lang['updatequantity'],
				'params' => $ajax_params,
				'json_params' => Tools::jsonEncode($ajax_params)
		));
		
		//echo $data->fetch();
		echo Tools::jsonEncode(array('use_parent_structure'=>false,'data'=> $data->fetch()));
		die;
		
	}
	
	
	/**
	 * update quantity of all items in pack, then check if type_product value is 2.
	 * if yes, add the pack items from input "inputPackItems"
	 *
	 * @param Product $product
	 * @return boolean
	 */
	public function ajaxProcessUpdateQuantity()
	{
		
		echo Tools::jsonEncode(array('use_parent_structure'=>false,'data'=> 'ssss'));
		die;
		
		/*Pack::deleteItems($product->id);
	
		// lines format: QTY x ID-QTY x ID
		if (Tools::getValue('type_product') == Product::PTYPE_PACK)
		{
			$items = Tools::getValue('inputPackItems');
			$lines = array_unique(explode('-', $items));
			// lines is an array of string with format : QTYxID
			if (count($lines))
				foreach ($lines as $line)
				if (!empty($line))
				{
					list($qty, $item_id) = explode('x', $line);
					if ($qty > 0 && isset($item_id))
					{
						if (!Pack::addItem((int)$product->id, (int)$item_id, (int)$qty))
							$this->errors[] = Tools::displayError('An error occurred while adding products to the pack.');
					}
				}
		}*/
	}
	
	
	
	public function getAvailablePackQuantity($id_product)
	{
		$pack_quantity = null;
			
		// if product is a pack
		if (Pack::isPack((int)$id_product))
		{
			$itemspacks = Pack::getItems((int)$id_product, Configuration::get('PS_LANG_DEFAULT'));
			// gets an array of quantities (quantity for the product / quantity in pack)
			$pack_quantities = array();
			foreach ($itemspacks as $itempack)
			{
				if (!$itempack->isAvailableWhenOutOfStock((int)$itempack->out_of_stock))
				{
					$pack_id_product_attribute = Product::getDefaultAttribute($itempack->id, 1);
					$pack_quantities[] = Product::getQuantity($itempack->id, $pack_id_product_attribute) / ($itempack->pack_quantity !== 0 ? $itempack->pack_quantity : 1);
				}
			}
		
			// gets the minimum
			$pack_quantity = $pack_quantities[0];
			//	print_r($pack_quantities);
			//exit;
			foreach ($pack_quantities as $value)
			{
				if ($pack_quantity > $value)
					$pack_quantity = $value;
					
			}
		}
		
		return $pack_quantity;
		
	}

	
	/**
	 * Get an array of pack items for display from the product object if specified, else from POST/GET values
	 *
	 * @param Product $product
	 * @return array of pack items
	 */
	public function getPackItems($product = null)
	{
	
		$stock_manager = StockManagerFactory::getManager();
		$pack_items = array();
	
		if ($product)
		{
	
			$i = 0;
				
			$nb_items = count($product->packItems);
			for ($i = 0; $i < $nb_items; ++$i)
			{
				$item = &$product->packItems[$i];
	
				// $item['stock']=$stock_manager->getProductPhysicalQuantities($item['id_product'], 0);
				$item['stock']=StockAvailable::getQuantityAvailableByProduct($item['id_product']);
			}
	
	
		}
	
		return $product->packItems;
	
	}
	
	
	/**
	 * Check stock for a given product or product attribute
	 * and manage available actions in consequence
	 *
	 * @param array $item reference to the current item
	 * @param bool $is_product_attribute specify if it's a product or a product variation
	 */
	protected function skipActionByStock(&$item, $is_product_variation = false)
	{
		$stock_manager = StockManagerFactory::getManager();
	
		//get stocks for this product
		$stock = $stock_manager->getProductPhysicalQuantities($item['id'], 0);
	
		//affects stock to the list for display
		//$item['stock'] = $stock;
	
		if ($stock <= 0)
		{
			//there is no stock, we can only add stock
			$this->addRowActionSkipList('removestock', array($item['id']));
			
		}
	}
	
	
	
	public function displayRemoveStockLink($token = null, $id, $name = null)
	{
	
		$data=$this->createTemplate('helpers/list/list_action_removestock.tpl');
		if (!array_key_exists('RemoveStock', self::$cache_lang))
			self::$cache_lang['RemoveStock'] = $this->l('RemoveStock', 'Helper');
		
		$ajax_params = $this->ajax_params;
		if (!is_array($ajax_params) || !isset($ajax_params['action']))
			$ajax_params['action'] = 'removestock';
		
		$data->assign(array(
				'id' => Tools::safeOutput($id),
				'controller' => str_replace('Controller', '', get_class($this->context->controller)),
				'token' => Tools::safeOutput($token != null ? $token : $this->token),
				'action' => self::$cache_lang['RemoveStock'],
				'params' => $ajax_params,
				'json_params' => Tools::jsonEncode($ajax_params)
		));
		
		return $data->fetch();
	}
	

	
	
	
}

/*if (!array_key_exists('RemoveStock', self::$cache_lang))
 self::$cache_lang['RemoveStock'] = $this->l('RemoveStock');

$ajax_params = $this->ajax_params;
if (!is_array($ajax_params) || !isset($ajax_params['action']))
	$ajax_params['action'] = 'removestock';

/*$this->context->smarty->assign(array(
		'id' => Tools::safeOutput($id),
		'controller' => str_replace('Controller', '', get_class($this->context->controller)),
		'token' => Tools::safeOutput($token != null ? $token : $this->token),
		'action' => self::$cache_lang['RemoveStock'],
		'params' => $ajax_params,
		'json_params' => Tools::jsonEncode($ajax_params)
));


$this->context->smarty->assign(array(
		'href' => self::$currentIndex.
		'&'.$this->identifier.'='.$id.
		'&removestock&token='.($token != null ? $token : $this->token),
		'action' => self::$cache_lang['RemoveStock'],
		'params' => $ajax_params,
		'json_params' => Tools::jsonEncode($ajax_params)
));

return $this->context->smarty->fetch('helpers/list/list_action_removestock.tpl');
*/

/*if (Pack::isPack((int)$item['id_product']))
 {
$itemspacks = Pack::getItems((int)$item['id_product'], Configuration::get('PS_LANG_DEFAULT'));
// gets an array of quantities (quantity for the product / quantity in pack)
$pack_quantities = array();
foreach ($itemspacks as $itempack)
{
if (!$itempack->isAvailableWhenOutOfStock((int)$itempack->out_of_stock))
{
$pack_id_product_attribute = Product::getDefaultAttribute($itempack->id, 1);
$pack_quantities[] = Product::getQuantity($itempack->id, $pack_id_product_attribute) / ($itempack->pack_quantity !== 0 ? $itempack->pack_quantity : 1);
}
}

// gets the minimum
$pack_quantity = $pack_quantities[0];
//	print_r($pack_quantities);
//exit;
foreach ($pack_quantities as $value)
{
if ($pack_quantity > $value)
	$pack_quantity = $value;
	
}
}*/